var express = require('express');
var router = express.Router();
var querystring = require('querystring');
var https = require('https');
var zlib = require('zlib');

router.get('/', function(request, response) {
    function fun(contents, resolve) {
        var options = {
            host: 'wds.modian.com',
            path: '/ajax_backer_list',
            method: 'POST',
            headers: {
                'Accept-Encoding': 'gzip, deflate, br',
                'Content-Length': contents.length,
                'Content-Type': 'application/x-www-form-urlencoded',
            }
        }
        var req = https.request(options, function(res) {

            console.log(res.statusCode);
            var json = [];
            res.on('data', function(chunk) {
                json.push(chunk);
            }).on('end', function() {
                json = Buffer.concat(json);
                zlib.gunzip(json, (err, data) => {

                    var jsonData = JSON.parse(data.toString());
                    var arr = jsonData.data;
                    var amount = 0;
                    for (let i = 0; i < arr.length; i++) {
                        amount += arr[i].total_back_amount
                    }

                    amount = amount.toFixed(2);

                    var backData = {};
                    backData.data = arr.slice(0, 5);
                    backData.totalamount = amount;
                    backData.time = Date.parse(new Date());
                    // response.render('index.html', backData)
                    resolve(backData)

                });
            })
        }).on('error', function(e) {
            console.log(e.message)
        });
        req.write(contents);
        req.end();
    }

    function promise1() {
        return new Promise(function(resolve, reject) {
            var contents = querystring.stringify({
                page: '1',
                type: '1',
                pro_id: '4937'
            });
            fun(contents, resolve)

        })
    }

    function promise2() {
        return new Promise(function(resolve, reject) {
            var contents = querystring.stringify({
                page: '1',
                type: '1',
                pro_id: '5146'
            });
            fun(contents, resolve)
        })
    }
    Promise.all([promise1(), promise2()]).then(function(results) {
        response.render('index.html', { 'rank': results, 'time': Date.parse(new Date()) })
    })
})

module.exports = router;